import tkinter
import time
import random
class Ball():
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_oval(0, 0, 15, 15, fill=color)
        canvas.move(self.id, 240, 175)
        level = [-9,-7,-5,-3,-1,1,3,5,7,9]
        self.x = random.choice(level)
        self.y = random.choice(level)
    def draw(self):
        canvas.move(self.id, self.x, self.y)
        pos = canvas.coords(self.id)
        level1 = [-9, -7, -5, -3, -1]
        level2 = [1, 3, 5, 7, 9]
        if pos[0] <=0:
            self.x = random.choice(level2)
        if pos[1] <=0:
            self.y = random.choice(level2)
        if pos[2] >=500:
            self.x = random.choice(level1)
        if pos[3] >=400:
            self.y = random.choice(level1)

class Paddle():
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_rectangle(0, 0, 300, 20, fill=color)
        canvas.move(self.id, 100, 300)
        self.x = 0
        self.y = 0
        self.canvas.bind_all('<KeyPress-Left>',self.turn_left)
        self.canvas.bind_all('<KeyPress-Right>', self.turn_Right)
    def turn_left(self,evt):
        self.x = -3
    def turn_Right(self,evt):
        self.x = 3
    def draw(self):
        canvas.move(self.id, self.x, self.y)
        pos = self.canvas.coords(self.id)
        if pos[0] <=0:
            self.x = 3
        if pos[1] <=0:
            self.y = 3
        if pos[2] >=500:
            self.x = -3
        if pos[3] >=400:
            self.y = -3

class Score():
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.score = 0
        self.id = canvas.create_text(450, 10, text =self.score, font=("Arial",15), fill=color)

tk = tkinter.Tk()
tk.title("弹球")
tk.update()
canvas = tkinter.Canvas(tk , width=500 ,height=400 ,)
canvas.pack()
tk.update()
ball1 = Ball(canvas,"red")
ball2 = Ball(canvas,"blue")
paddle = Paddle(canvas,"yellow")
score = Score(canvas,"red")
while 1:
    ball1.draw()
    ball2.draw()
    paddle.draw()
    tk.update_idletasks()
    tk.update()
    time.sleep(0.01)